//
//  WNSubVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/31.
//

import UIKit

class WNSubVC: WNBaseVC {

    lazy var subView: SubTopView = {
        let view = SubTopView()
        return view
    }()

    lazy var subBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 18)
        btn.rx.tap.bind{ [weak self] in
            self?.tapSubBtn()
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(8)
        return btn
    }()
    
    lazy var subTextView: IQTextView = {
        let view = IQTextView()
        view.font = .wn_font(name: .bold, size: 12)
        view.showsVerticalScrollIndicator = false
        view.wn_appendLinkString(string: "1. Login daily starting from the day after your purchase, tap on 'Check-in' and daily check-in gift.\n2. You can receive the check-in gifts for 30 consecutive days.\nSubscription Agreement\nPayment: The purchase will be charged to your Apple Store account.\nRenewal: Your subscription will renew automatically. Subscription are automatically charged each billing period whether monthly oranother period, and you may be charged no more than 24 hours before the beginning of each billing period until you cancel your subscription.\nCancellation: You may cancel a subscription at any time more than 24 hours before your renewal date.\n\nManage: ")
        view.wn_appendLinkString(string: "You can view, change, or cancel vour subscription.", withURLString: "https://apps.apple.com/account/subscriptions")
        view.textColor = .init(named: "gray_999999")
        view.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.init(named: "red_FE95B4")!]
        view.isEditable = false
        view.delegate = self
        view.contentInset = .init(top: -10, left: 0, bottom: 0, right: 0)
        return view
    }()

    lazy var privacyView: IQTextView = {
        let view = IQTextView()
        view.font = .wn_font(name: .bold, size: 12)
        view.showsVerticalScrollIndicator = false
        view.wn_appendLinkString(string: "Service Agreement", withURLString: WNConfigure.WNURL.wn_Agreement)
        view.wn_appendLinkString(string: " and ")
        view.wn_appendLinkString(string: "Privacy Policy", withURLString: WNConfigure.WNURL.wn_Privacy)
        view.wn_appendLinkString(string: "\nAgreement for Subscription Services")
        view.textColor = .init(named: "gray_999999")
        view.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.init(named: "gray_666666")!]
        view.isEditable = false
        view.delegate = self
        view.contentInset = .init(top: -10, left: 0, bottom: 0, right: 0)
        view.textAlignment = .center
        return view
    }()
    
    var subModel: SubModel? {
        didSet {
            subView.model = subModel
            handleCheckStatus()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewConfig() {
        view.addSubview(subView)
        view.addSubview(subBtn)
        view.addSubview(privacyView)
        view.addSubview(subTextView)
        subView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight+40)
            make.left.right.equalTo(0)
            make.height.equalTo(scaleWidth(162))
        }
        subBtn.snp.makeConstraints { make in
            make.top.equalTo(subView.snp.bottom).offset(20)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(44)
        }
        privacyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-TabBarMargin-12)
            make.width.equalTo(300)
            make.height.equalTo(30)
        }
        subTextView.snp.makeConstraints { make in
            make.top.equalTo(subBtn.snp.bottom).offset(20)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(privacyView.snp.top).offset(-20)
        }
    }
    
    override func dataConfig() {
        pageName = "VIP"
        navView.titleName = "VIP"
        navView.rightBtnTitle = "Restore"
        navView.rightClosure = { [weak self] in
            WNSubManager.shared.restoreSubscribe(self?.subModel?.sub?.pid ?? "", self?.subModel?.sub?.password ?? "")
        }
        getSubDetail()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.subscribeNoti, object: nil, queue: nil) { [weak self] not in
            self?.getSubDetail()
            self?.subModel?.isDing = 1
        }
    }
}

extension WNSubVC: UITextViewDelegate {
    
    func tapSubBtn() {
        if subBtn.titleLabel?.text == "TOP UP" {
            WNBuriedManager.shared.logProductItem(subModel?.sub?.pid ?? "", subModel?.sub?.name ?? "", subModel?.sub?.price ?? 0.0)
            WNSubManager.shared.creatSubscribeOrder(subModel?.sub?.pid ?? "", subModel?.sub?.price ?? 0.0)
        }else if subBtn.titleLabel?.text == "CHECK IN" {
            checkInRequest()
        }
    }

    func handleCheckStatus() {
        if subModel?.isDing == 1 {
            if subModel?.checkInOrNOt == 1 {
                subBtn.setTitle("Received", for: .normal)
                subBtn.backgroundColor = .init(named: "gray_E0E8EE")
            }else {
                subBtn.setTitle("CHECK IN", for: .normal)
                subBtn.backgroundColor = WNColor.Fade().left2right(.init(width: ScreenW-40, height: 44))
            }
        }else {
            subBtn.setTitle("TOP UP", for: .normal)
            subBtn.backgroundColor = WNColor.Fade().left2right(.init(width: ScreenW-40, height: 44))
        }
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == WNConfigure.WNURL.wn_Privacy {
            wn_pushWebVC(URL.absoluteString, "Privacy Policy")
        }
        if URL.absoluteString == WNConfigure.WNURL.wn_Privacy {
            wn_pushWebVC(URL.absoluteString, "Service Agreement")
        }
        if URL.absoluteString == "https://apps.apple.com/account/subscriptions" {
            if UIApplication.shared.canOpenURL(URL) {
                UIApplication.shared.open(URL, options: [:], completionHandler: nil)
            }
        }
        return false
    }

    func getSubDetail() {
        provider_recommend.rx.request(.getSubDetail)
            .asObservable().mapModel(BaseModel<SubModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let data = model.data {
                    self?.subModel = data
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    func checkInRequest() {
        provider_recommend.rx.request(.checkInSub)
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let _ = model.data {
                    self?.wn_toast("Check in successed")
                    self?.getSubDetail()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
}
